//
//  ProjectCell.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/5/24.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import FSPagerView

class ProjectCell: UITableViewCell {

    //产品名称
    @IBOutlet weak var lblProductName: UILabel!
    //产品编号
    @IBOutlet weak var lblProductNo: UILabel!
    //产品图片
    @IBOutlet weak var vwImageContent: UIView!
    //商品选择视图
    @IBOutlet weak var vwCommodity: UIView!
    //已选商品套餐
    @IBOutlet weak var lblSelectCommodity: UILabel!
    //投资进度条
    @IBOutlet weak var progressBar: UIProgressView!
    //投资显示标签
    @IBOutlet weak var lblProgress: UILabel!
    //状态
    @IBOutlet weak var lblStatus: UILabel!
    //剩余数量
    @IBOutlet weak var lblNum: UILabel!
    //认购按钮
    @IBOutlet weak var btnOrder: UIButton!
    //限额说明图片
    @IBOutlet weak var ivTips: UIImageView!
    //状态展示图片
    @IBOutlet weak var ivStatus: UIImageView!
    //限额说明按钮
    @IBOutlet weak var btnTips: UIButton!
    //商品列表视图
    @IBOutlet weak var vwCommodityList: CommodityListView!
    
    let disposeBag = DisposeBag()
    let BANNER_CELL_ID = "project_image_banner_cell"
    var arrImageUrl:[String] = [String]()
    var pageView:FSPagerView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.selectionStyle = .none
        
        self.ivTips.addTapGesture(target: self, selector: #selector(showTips))
        self.btnTips.addTarget(self, action: #selector(showTips), for: .touchUpInside)
        
        self.vwCommodity.addTapGesture(target: self, selector: #selector(openPackageSelectView))
        
        //认购按钮
        btnOrder.rx.tap.asObservable()
            .subscribe(onNext: { [unowned self] _ in
                self.openManageSelect()
            }).disposed(by: disposeBag)
        
        pageView = FSPagerView(frame: .zero)
        pageView.dataSource = self
        pageView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: BANNER_CELL_ID)
        pageView.automaticSlidingInterval = 3.0
        vwImageContent.addSubview(pageView)
        pageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    //打开选择经理人弹窗
    func openManageSelect() {
        guard let _ = MainTools.shared.userModel else {
            self.parentViewController?.navigationController?.tabBarController?.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
            self.parentViewController?.navigationController?.tabBarController?.present((UIStoryboard(name: "LoginAndRegister", bundle: nil).instantiateInitialViewController() as? UINavigationController) ?? UINavigationController(), animated: true, completion:nil)
            return
        }
        
        let vwSelect = (Bundle.main.loadNibNamed("ManagerSelectView", owner: nil, options: nil)?.first as? ManagerSelectView) ?? ManagerSelectView()
        vwSelect.projectModel = self.model
        vwSelect.show()
    }
    
    @objc func showTips() {
        let strTips = (self.parentViewController as? ProjectController)?.tips ?? ""
        let alert = UIAlertView(title: "说明", message: strTips, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "确定")
        alert.show()
    }
    
    var model:ProjectModel = ProjectModel() {
        didSet {
            if model.progress_status == "0" {
                btnOrder.setTitle("即将开放", for: .normal)
                btnOrder.setTitleColor(UIColor.white, for: .normal)
                btnOrder.backgroundColor = UIColor(hex: 0xff931f)
                btnOrder.isEnabled = false
                ivStatus.image = UIImage(named: "product-yrz")
                lblStatus.text = "即将开放"
            } else if model.progress_status == "1" {
                btnOrder.setTitleColor(UIColor.white, for: .normal)
                btnOrder.backgroundColor = UIColor(hex: 0x2fd6a2)
                ivStatus.image = UIImage(named: "product-zcz")
                tickCount = Int(model.tick_count_time) ?? 0
                lblStatus.baselineAdjustment = .alignBaselines
                stopTick()
                if tickCount > 0 { //即将开放
                    btnOrder.isEnabled = false
                    btnOrder.setTitle("即将开放", for: .normal)
                    startTick()
                } else { //已经开放
                    btnOrder.isEnabled = true
                    btnOrder.setTitle("立即认购", for: .normal)
                    lblStatus.text = "认筹中"
                    lblStatus.textColor = .black
                }
            } else if model.progress_status == "2" {
                btnOrder.setTitle("认购结束", for: .normal)
                btnOrder.setTitleColor(UIColor(hex:0x5d5d5d), for: .normal)
                btnOrder.backgroundColor = UIColor(hex: 0xe5e5e5)
                btnOrder.isEnabled = false
                ivStatus.image = UIImage(named: "product-yjs")
                lblStatus.text = "已完成"
            }
            
            lblProductName.text = model.name
            lblProductNo.text = "产品编号：\(model.number)"
            let dbPrecent = (Double(model.buy_amount) ?? 0.0) / (Double(model.amount) ?? 1.0)
            progressBar.progress = Float(dbPrecent)
            lblProgress.text = "当前进度:\(Int(dbPrecent * 100))%"
            lblNum.text = model.pro_num
            arrImageUrl = model.img.components(separatedBy: ",").map { ActionURL.HOST + $0 }
            self.pageView.reloadData()
            lblSelectCommodity.text = "商品组合\(model.arrPackage.first?.type ?? "")"
            vwCommodityList.arrModel = model.arrPackage.first?.arrCommodity ?? [CommodityModel]()
            
            selectType = model.arrPackage.first?.type ?? ""
            arrPack.removeAll()
            for pack in model.arrPackage {
                arrPack.append(pack.type)
            }
        }
    }
    
    var tm:Timer?
    var tickCount:Int = 0
    
    func startTick() {
        stopTick()
        tickTime()
        tm = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tickTime), userInfo: nil, repeats: true)
    }
    
    @objc func tickTime() {
        let tpTime = getHMSTime(time: tickCount)
        lblStatus.text = "\(tpTime.h)时\(tpTime.m)分\(tpTime.s)秒"
        lblStatus.textColor = UIColor(hex:0xFF931F)
        lblStatus.setStrsArrStyle(strs: ["时","分","秒"], color: .black, fontSize: 11)
        
        tickCount -= 1
        if tickCount <= 0 {
            btnOrder.isEnabled = true
            btnOrder.setTitle("立即认购", for: .normal)
            lblStatus.text = "认筹中"
            lblStatus.textColor = .black
            stopTick()
        }
    }
    
    func stopTick() {
        tm?.invalidate()
        tm = nil
    }
    
    func getHMSTime(time:Int) -> (h:String,m:String,s:String) {
        let hours = time/3600
        let mins = (time - 3600 * hours) / 60
        let secs = time - 3600 * hours - 60 * mins
        var strMins = ""
        var strSecs = ""
        
        if mins > 0 && mins < 10 {
            strMins = "0\(mins)"
        } else if mins > 9 {
            strMins = "\(mins)"
        } else if mins == 0 {
            strMins = "00"
        }
        
        if secs > 0 && secs < 10 {
            strSecs = "0\(secs)"
        } else if secs > 9 {
            strSecs = "\(secs)"
        } else if secs == 0 {
            strSecs = "00"
        }
        return (h:"\(hours)",m:strMins,s:strSecs)
    }
    
    var arrPack:[String] = [String]()
    var selectType:String = ""
    //打开套餐选择
    @objc func openPackageSelectView() {
        let vwPick = CBPickView(arrData: self.arrPack, strTitle: "请选择商品组合") { [unowned self] (strSelectType) in
            if self.selectType == strSelectType {
                return
            }
            
            self.selectType = strSelectType
            for pack in self.model.arrPackage {
                if pack.type == strSelectType {
                    pack.isSelect = true
                    self.lblSelectCommodity.text = "商品组合\(strSelectType)"
                    self.vwCommodityList.arrModel = pack.arrCommodity
                } else {
                    pack.isSelect = false
                }
            }
        }
        vwPick.show(strSelectValue: selectType)
    }
    
    
    
    @objc func pushToProductDetail(_ sender: UITapGestureRecognizer) {
        let productVc = ProductController()
        productVc.hidesBottomBarWhenPushed = true
        self.parentViewController?.navigationController?.pushViewController(productVc, animated: true)
    }
    
    
}

extension ProjectCell: FSPagerViewDataSource {
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return arrImageUrl.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: BANNER_CELL_ID, at: index)
        cell.imageView?.kf.setImage(with: URL(string: arrImageUrl[index]), placeholder: UIImage(named: "bg_place_holder"), completionHandler: nil)
        return cell
    }
    
}
